package sy.controller;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.DeviceEnum;
import cn.jpush.api.push.MessageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sy.model.TPush;
import sy.pageModel.DataGrid;
import sy.pageModel.Json;
import sy.pageModel.PageHelper;
import sy.service.PushServiceI;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
@RequestMapping("/pushController")
public class PushmsgController extends BaseController {

        @Autowired
        private PushServiceI pushService;

		private static final String appKey ="c83a260b0daf7a5163e2b10f";
	    private static final String masterSecret = "e4427be1ab55c8b7f10d3404";
	
		//提交建议
		@RequestMapping("/pushmsg")
		@ResponseBody
		public Json pushmsg(HttpServletResponse response,HttpServletRequest request, HttpSession session) {
			Json j = new Json();
			String msgcontent=request.getParameter("pushmsg");
			JPushClient  jpushAndroid = new JPushClient(masterSecret, appKey, 0, DeviceEnum.Android, false);
			 MessageResult result = jpushAndroid.sendNotificationAll(msgcontent);

			 String msg=result.getErrorMessage();
		   	 j.setMsg(msg);
			
			return j;
		}


    @RequestMapping("/batchDelete")
    @ResponseBody
    public Json batchDelete(String ids, HttpSession session) {
        Json j = new Json();
        if (ids != null && ids.length() > 0) {
            for (String id : ids.split(",")) {
                if (id != null) {
                    this.delete(id, session);
                }
            }
        }
        j.setMsg("批量删除成功！");
        j.setSuccess(true);
        return j;
    }

    //发布公告信息
    @RequestMapping("/uploadcontent")
    @ResponseBody
    public Json uploadcontent(HttpServletResponse response,HttpServletRequest request, HttpSession session)throws Exception {
        Json j = new Json();
        String content=request.getParameter("content");
        String imageurl=request.getParameter("imageurl");
        String title=request.getParameter("title");

        String htmlpage=getHead(content);
        TPush tPush=new TPush();

        try {

            ///将字符串写入文件
            ServletContext context=request.getSession().getServletContext();
            String realpath = context.getRealPath("/ad");
            File filelocal = new File(realpath);
            if(!filelocal.exists()) filelocal.mkdirs();

            String filename= UUID.randomUUID().toString();
            FileOutputStream out = new FileOutputStream(filelocal.getAbsolutePath()+"\\"+filename+".html");
            out.write(htmlpage.getBytes());
            out.close();

            tPush.setTitle(title);

            SimpleDateFormat format=  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            tPush.setPublistime(format.format(new Date()));
            tPush.setLinkAddress("/ad/"+filename+".html");
            tPush.setContent(content);

            pushService.add(tPush);

            //推送消息
            JPushClient  jpushAndroid = new JPushClient(masterSecret, appKey, 0, DeviceEnum.Android, false);
           // MessageResult result = jpushAndroid.sendNotificationAll();
            MessageResult result= jpushAndroid.sendCustomMessageAll(title,"/ad/"+filename+".html");

            String msg=result.getErrorMessage();
            j.setMsg(msg);


        } catch (Exception e) {
            j.setMsg("发布失败！");
            j.setSuccess(false);
            e.printStackTrace();
        }

        return j;
    }
    public  String getHead(String content){
        String head="<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>" +
                "<html>" +
                "<head>" +
                "  <meta http-equiv='Content-Type' content='text/html;' charset='gbk' />" +
                "  <meta name='viewport' content='initial-scale=1.0, user-scalable=no'>" +
                "  <meta name='apple-mobile-web-app-capable' content='yes'>" +
                "  <meta name='apple-mobile-web-app-status-bar-style' content='black'>" +
                "  <title></title>" +
                " </head><body> ";

        head+=content;


        String end="</body></html>";
        return head+=end;
    }

    @RequestMapping("/dataGrid")
    @ResponseBody
    public DataGrid dataGrid(TPush tPush, PageHelper ph) {

        return pushService.dataGrid(tPush, ph);
    }
    @RequestMapping("/delete")
    @ResponseBody
    public Json delete(String id, HttpSession session) {
        Json j = new Json();
        if (id != null ) {// 不能删除自己
            pushService.delete(id);
        }
        j.setMsg("删除成功！");
        j.setSuccess(true);
        return j;
    }

}
